package me.shihao.serialportdemo

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ScrollView
import kotlinx.android.synthetic.main.activity_main.*
import me.shihao.serialportdemo.serialport.SerialPortManager
import java.math.BigDecimal
import java.math.RoundingMode
import kotlin.concurrent.timer

const val ACTION_USB_DEVICE_PERMISSION = "receiver.action.USB_PERMISSION"

class MainActivity : AppCompatActivity() {

    private val TAG = javaClass.simpleName
    private lateinit var broadcastReceiver: BroadcastReceiver

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //注册usb设备连接广播
        val filter = IntentFilter()
        filter.addAction(ACTION_USB_DEVICE_PERMISSION)
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
        broadcastReceiver = UsbDeviceBroadcastReceiver()
        this.registerReceiver(broadcastReceiver, filter)
        SerialPortManager.instance.addOnReceivedDataListener(object :
            SerialPortManager.OnReceivedDataListener {
            override fun onReceivedData(data: String) {
                runOnUiThread {
                    tv_data.append(data)
                    tv_data.append("\n")
                    scrollView.fullScroll(ScrollView.FOCUS_DOWN)
                }
                val regex = Regex("0A0D(.*?)0A0D")
                val result = regex.find(data.toUpperCase())
                result?.let {
                    val text = result.groupValues[1]
                    if (text.length == 10 + 10 + 12 + 8) {
                        val textWeight = text.substring(0, 10)
                        val textPrice = text.substring(14, 24)
                        val textTotal = text.substring(28)
                        runOnUiThread {
                            tv_weight.text = "净重：${format(textWeight, 3)}"
                            tv_unit_price.text = "单价：${format(textPrice, 2)}"
                            tv_total_price.text = "总价：${format(textTotal, 2)}"
                        }
                    }
                }
            }
        })
//        val regex = Regex("0A0D(.*?)0A0D")
//        val result = regex.find(data.toUpperCase())
//        result?.let {
//            val text = result.groupValues[1]
//            if (text.length == 10 + 10 + 12 + 8) {
//                val textWeight = text.substring(0, 10)
//                val textPrice = text.substring(14, 24)
//                val textTotal = text.substring(28)
//                runOnUiThread {
//                    tv_weight.text = "净重：${format(textWeight, 3)}"
//                    tv_unit_price.text = "单价：${format(textPrice, 2)}"
//                    tv_total_price.text = "总价：${format(textTotal, 2)}"
//                }
//            }
//        }
    }

    private fun format(text: String, scale: Int): String {
        var result = ""
        for (index in text.indices step 2) {
            val m = "${text[index]}${text[index + 1]}"
            if (m == "20") {
                result += "0"
            } else {
                result += text[index + 1]
            }
        }
        val bigDecimal = BigDecimal(result)
        val num = bigDecimal.divide(if (scale == 2) BigDecimal(100) else BigDecimal(1000))
            .setScale(scale, RoundingMode.CEILING)
        return num.toString()
    }

    override fun onDestroy() {
        super.onDestroy()
        this.unregisterReceiver(broadcastReceiver)
        SerialPortManager.instance.disconnectDevice()
    }

    private fun requestPermission(device: UsbDevice) {
        val manager = getSystemService(Context.USB_SERVICE) as UsbManager
        if (!manager.hasPermission(device)) {
            Log.d(TAG, "没有权限,开始申请权限")
            //申请权限
            val pendingIntent =
                PendingIntent.getBroadcast(this, 0, Intent(ACTION_USB_DEVICE_PERMISSION), 0)
            manager.requestPermission(device, pendingIntent)
        }
    }

    inner class UsbDeviceBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as UsbDevice?
            if (intent.action == UsbManager.ACTION_USB_DEVICE_ATTACHED) {
                //插上usb设备
                Log.d(TAG, "检测到usb设备插入")
                usbDevice?.let {
                    val count = it.interfaceCount
                    if (count > 0) {
                        val manager = getSystemService(Context.USB_SERVICE) as UsbManager
                        if (manager.hasPermission(it)) {
                            SerialPortManager.instance.connectDevice(this@MainActivity, it)
                        } else {
                            requestPermission(it)
                        }
                    }
                }
            } else if (intent.action == UsbManager.ACTION_USB_DEVICE_DETACHED) {
                //拔掉usb设备
                Log.d(TAG, "检测到usb设备拔出")
                usbDevice?.let {
                    val count = it.interfaceCount
                    if (count > 0) {
                        //串口设备拔出
                        SerialPortManager.instance.disconnectDevice()
                    }
                }
            } else if (intent.action == ACTION_USB_DEVICE_PERMISSION) {
                val isGranted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                if (isGranted) {
                    //用户已授权
                    usbDevice?.let {
                        val count = it.interfaceCount
                        if (count > 0) {
                            //串口设备
                            Log.d(TAG, "用户已授权，开始连接设备")
                            SerialPortManager.instance.connectDevice(this@MainActivity, it)
                        }
                    }
                } else {
                    //用户未授权
                    Log.d(TAG, "用户未授权")
                }

            }
        }
    }
}